<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-5-12
 * Time: 下午10:33
 */
namespace builder\console\controllers;

use Ulue;
use ulue\cli\CliInteract;
use ulue\web\Module;
use builder\console\parts\ConsoleController;

class CtrlController extends ConsoleController
{
    protected $tplOptions = [
        '{author}'                 => 'inhere',
        '{date}'                   => '',
        '{ControllerClassname}'    => '',
        '{namespace}'              => '',
        '{parentClass}'            => 'ulue\web\Controller',
        '{parentClassname}'        => 'Controller',
    ];

    protected $name;

    protected $module;

    protected $type   = 'web';

    protected $suffix = 'Controller';

    public function init()
    {
        $this->tplOptions['{date}'] = date('Y-m-d H:i:s');
    }

    /**
     * [indexCommand description]
     * @param  string $module
     * @param  string $name
     * @param  string $type  'web' 'cli'
     */
    public function indexCommand($module='', $name='', $type='web')
    {
        $ops = $this->prepareAndCheck($module, $name, $type);

        $this->createFile( array_merge($this->tplOptions,$ops) );
    }

    public function prepareAndCheck($module, $name, $type)
    {
        if (!$module) {
            $module = CliInteract::loopAsk('To create a file to which module name: ', 2);
        }

        if (!$module) {
            throw new \DInvalidArgumentException('the module name is required!');
        }

        if ( !Module::exists($module) ) {
            throw new \DInvalidArgumentException('the module "'.$module.'" don\'t exists!');
        }

        if (!$name) {
            $name = CliInteract::loopAsk('entry Controller name: ', null, 2);
        }

        if (!$name) {
            throw new \DInvalidArgumentException('the Controller name is required!');
        }

        $types = [ 1 => 'web', 2 => 'action' , 3 => 'cli'];

        if (!$type) {
            $key = CliInteract::choice('please choice type: ', $types);
            $type = $types[$key];
        }

        if ( !in_array($type, ['web', 'action' ,'cli'])) {
            throw new \DInvalidArgumentException("the type only allow ['web', 'action' ,'cli']! you entry [$type]");
        }

        $this->module = $module;
        $this->name  = $name;
        $this->type  = $type;

        $ops['{ControllerClassname}'] = $name . $this->suffix;

        $namespace = CliInteract::loopAsk("entry Controller's namespace \n: ", null, 2);
        $ops['{namespace}'] = $namespace;

        $parentClass = CliInteract::loopAsk("entry parent Controller full class name(include namespace)\n: ", null, 2);

        $ops['{parentClass}'] = $parentClass;
        $ops['{parentClassname}'] = basename($parentClass);

        CliInteract::panel($ops, 'Controller info');

        return $ops;
    }

    public function createFile(array $tplOptions)
    {
        # code...
    }
}